import { cloneElement, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Form, Modal } from 'antd';

/**
 * 表单弹窗组件
 *
 * @param {string} title 弹窗标题
 * @param {string} name 表单名称
 * @param {ReactNode} trigger 触发弹窗的控件
 * @param {ReactNode} formItems 表单项
 * @param {Function} onFinish 表单提交回调
 */
export default forwardRef(function FormModal({ title, name, trigger, formItems, onFinish }, ref) {
  useImperativeHandle(ref, () => ({
    open: () => setOpen(true),
    close: () => setOpen(false),
    form: form
  }));

  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (!open && form) {
      form?.resetFields();
    }
  }, [open, form]);

  // 点击触发控件
  const triggerWithOnClick = cloneElement(trigger ?? <></>, {
    onClick: () => setOpen(true)
  });

  // 提交表单
  const handleSubmit = async (data) => {
    onFinish && onFinish(data);
  };

  return (
    <>
      {triggerWithOnClick}
      <Modal
        title={title}
        open={open}
        onOk={form?.submit}
        onCancel={() => setOpen(false)}
        width={300}
      >
        <Form form={form} name={name} layout="vertical" onFinish={handleSubmit}>
          {formItems}
        </Form>
      </Modal>
    </>
  );
});
